package test.threadlocal;

import java.util.Random;


public class Client implements Runnable
{
	 ThreadLocal<Student> studentLocal = new ThreadLocal<Student>();
	 Student student = null;
	
	Random random = new Random();
	
	public static void main(String[] args)
	{
		for(int i=0;i<10;i++)
		{
			doProcess(i);	
		}
	}
	
	private static void doProcess(int i)
	{
		Client c = new Client();
		Thread a = new Thread(c,"a"+i+" Thread");
		a.start();
//		Thread b = new Thread(c,"b"+i+"  Thread");
//		b.start();
	}
	
	private  Student getStudent()
	{
		if(studentLocal.get() != null && !"".equals(studentLocal.get()))
		{
			return studentLocal.get();
		}else{
			student = new Student();
			studentLocal.set(student);
			return student;
		}
	}

	@Override
	public void run()
	{
		try
		{
			int nowAge = random.nextInt(100);
			getStudent().setAge(nowAge);
			System.out.println(Thread.currentThread().getName()+" : 给对象"+getStudent()+"设置了age="+nowAge);
			Thread.sleep(5000);
		} catch (InterruptedException e)
		{
			e.printStackTrace();
		}
		System.out.println(Thread.currentThread().getName()+" : 对应的对象"+getStudent()+"的age="+getStudent().getAge());	
	}
}

